package com.gary.lockDemo;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author peng_rui
 * @date 2022/3/14
 */

class LShare {
    private int num = 0;

    //创建ReentrantLock
    Lock lock = new ReentrantLock();
    //创建condition条件，效果类似与 Object的 wait notifyAll
    Condition condition = lock.newCondition();

    /**
     * +
     */
    public void incr() {
        //上锁
        lock.lock();
        //判断
        try {
            while (num != 0) {
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //干活
            num++;
            System.out.println(Thread.currentThread().getName() + " :: " + num);
            //通知
            condition.signalAll();

        } finally {
            //解锁
            lock.unlock();
        }
    }

    /**
     * -
     */
    public void decr() {
        //上锁
        lock.lock();
        //判断
        try {
            while (num == 0) {
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //干活
            num--;
            System.out.println(Thread.currentThread().getName() + " :: " + num);
            //通知
            condition.signalAll();
        } finally {
            //解锁
            lock.unlock();
        }

    }
}
public class LAddSubDemo {
    public static void main(String[] args) {
        LShare lShare = new LShare();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                lShare.incr();
            }
        }, "AA").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                lShare.decr();
            }
        }, "BB").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                lShare.incr();
            }
        }, "CC").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                lShare.decr();
            }
        }, "DD").start();
    }
}
